package com.supermarket.manage.buiness.handler;

import com.alibaba.fastjson.JSON;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份验证异常拦截器
 *
 * @author: Faxon
 * @data: 2020/2/22
 */
@Component
public class MyAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if (cause instanceof InvalidTokenException) {
                response.getWriter().write(
                        JSON.toJSONString(
                                new ResponseResult<>(CodeStatus.TOKEN_EXPIRED, "令牌已过期，请重新登录")
                        )
                );
            } else {
                response.getWriter().write(
                        JSON.toJSONString(
                                new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "请登录后访问")
                        )
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
